package cn.edu.cuit.elena.web.service;

import java.io.IOException;

import javax.security.auth.message.callback.PrivateKeyCallback.Request;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.cuit.elena.transaction.DataSourceManager;
import cn.edu.cuit.elena.transaction.system.UserContext;
import cn.edu.cuit.elena.transaction.system.priviledge.PriviledgeManager;
import cn.edu.cuit.elena.trace.Tracer;

public class ServiceServlet
    extends HttpServlet
{
    private static final long serialVersionUID = 1L;

    public static enum ServiceConstants
    {
        USERCONTEXT( "usercontext" ), ILLEGAL_ACCESS( "/index.html?error=illegal_access" ), INDEX( "system/index.jsp" );

        private String mark;

        ServiceConstants(String mark)
        {
            this.mark = mark;
        }

        public String mark()
        {
            return mark;
        }
    }

    protected void doGet( HttpServletRequest req, HttpServletResponse resp ) throws ServletException, IOException
    {
        doPost( req, resp );
    }

    protected void doPost( HttpServletRequest req, HttpServletResponse resp ) throws ServletException, IOException
    {
        if("logout".equals( req.getParameter( "kind" ) )){
            req.getSession().invalidate();
            return;
        }
        
        UserContext userContext = new UserContext( req.getParameter( "username" ), req.getParameter( "password" ) );
       
      
        
        if( PriviledgeManager.authorize( userContext ) )
        {
            DataSourceManager.createDataSourceManagerForUser( userContext );
            req.getSession().setAttribute( ServiceConstants.USERCONTEXT.mark(), userContext );
            req.getRequestDispatcher(  ServiceConstants.INDEX.mark() ).forward( req, resp );

            Tracer.infoTrace( this.getClass(), "User : " + userContext.getUserName() + " " + userContext.getPassword()
                + " login successfully.", null );
        }
        else
        {
            resp.sendRedirect( req.getContextPath() + ServiceConstants.ILLEGAL_ACCESS.mark() );
            Tracer.infoTrace( this.getClass(), "User : " + userContext.getUserName() + " " + userContext.getPassword()
                + " login fail.", null );
        }

    }

}
